#include<iostream>
#include<unordered_map>

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

int pathSum(TreeNode* root, int targetSum) {
    int res = 0;
    unordered_map<long long, int> m{ {0,1} };
    auto dfs = [&](auto&& dfs, TreeNode* cur, long long s) {
        if (!cur)    return;
        s += cur->val;
        res += m[s - targetSum];
        m[s]++;
        dfs(dfs, cur->left, s);
        dfs(dfs, cur->right, s);
        m[s]--;
        };
    dfs(dfs, root, 0);
    return res;
}